package com.lczyfz.campusinfo.modules.wechat.service;

import com.alibaba.fastjson.JSON;
import com.drew.lang.StringUtil;
import com.lczyfz.campusinfo.common.utils.SpringContextHolder;
import com.lczyfz.campusinfo.common.utils.StringUtils;
import com.lczyfz.campusinfo.modules.sys.entity.User;
import com.lczyfz.campusinfo.modules.sys.security.SystemAuthorizingRealm;
import com.lczyfz.campusinfo.modules.sys.security.UsernamePasswordToken;
import com.lczyfz.campusinfo.modules.sys.service.SystemService;
import com.lczyfz.campusinfo.modules.sys.utils.UserUtils;
import com.lczyfz.campusinfo.modules.user.utils.ServerResponse;
import com.lczyfz.campusinfo.modules.wechat.entity.WeChatBaseResult;
import com.lczyfz.campusinfo.modules.wechat.entity.WeChatUser;
import com.lczyfz.campusinfo.modules.wechat.utils.HttpClientUtils;
import com.lczyfz.campusinfo.modules.wechat.utils.WeChatUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Service
@Transactional(readOnly = true)
public class WeChatService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    public WeChatUser getWeChatUserInfo(String openid) {
        logger.debug("WeChatUtils.ACCESS_TOKEN = " + WeChatUtils.ACCESS_TOKEN);
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + WeChatUtils.ACCESS_TOKEN
                + "&openid=" + openid + "&lang=zh_CN";
        String result = HttpClientUtils.sendHttpGet(url);
        logger.debug("result1 = " + result);
        WeChatUser weChatUser = JSON.parseObject(result, WeChatUser.class);
        //失败的时候再尝试一次，刷新Access_Token
        if (!WeChatUtils.checkErrcode(weChatUser)) {
            url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + WeChatUtils.ACCESS_TOKEN
                    + "&openid=" + openid + "&lang=zh_CN";
            result = HttpClientUtils.sendHttpGet(url);
            logger.debug("result2 = " + result);
            weChatUser = JSON.parseObject(result, WeChatUser.class);
        }
        logger.debug("weChatUser = " + weChatUser);
        logger.debug("weChatUser.getErrcode = " + weChatUser.getErrcode());
        return weChatUser;
    }
    public boolean replyTextMessage(HttpServletResponse response, String toUserName, String fromUserName, Long createTime, String msgType, String content) {

        StringBuffer str = new StringBuffer();
        str.append("<xml>");
        str.append("<ToUserName><![CDATA[" + toUserName + "]]></ToUserName>");
        str.append("<FromUserName><![CDATA[" + fromUserName + "]]></FromUserName>");
        str.append("<CreateTime>" + createTime + "</CreateTime>");
        str.append("<MsgType><![CDATA[" + msgType + "]]></MsgType>");
        str.append("<Content><![CDATA[" + content + "]]></Content>");
        str.append("</xml>");
        logger.debug("str = " + str.toString());
        try {
            response.getWriter().write(str.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 微信端登录
     * @param request
     * @param openId
     * @return 登录用户id
     */
    public User doLoginMainPlatform(HttpServletRequest request, String openId) {
        String password = "admin";
        boolean rememberMe = true;
        String host = StringUtils.getRemoteAddr(request);
        String captcha = WebUtils.getCleanParam(request, "validateCode");
        boolean mobile = false;
        boolean weChat = true;
        UsernamePasswordToken token = new UsernamePasswordToken(openId, password.toCharArray(), rememberMe, host, captcha, mobile, weChat);
        if (token == null) {
            String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
                    "must be created in order to execute a login attempt.";
            throw new IllegalStateException(msg);
        }

        SystemAuthorizingRealm.Principal principal = null;
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            principal = UserUtils.getPrincipal();
//            logger.debug("principal = " + principal);
//            logger.debug("UserUtils.get(principal.getId()) = " + UserUtils.get(principal.getId()).getLoginName());
        } catch (AuthenticationException e) {
            logger.debug("AuthenticationException = " + e.getMessage());
        }
        User user = null;
        if(principal != null){
            user = UserUtils.getUser();
        }
        return user;
    }

    //对于认证服务号虽然开发者使用高级群发接口的每日调用限制为100次，但是用户每月只能接收4条，无论在公众平台网站上，
    // 还是使用接口群发，用户每月只能接收4条群发消息，多于4条的群发将对该用户发送失败；
    public ServerResponse sendTextMsgToMass(String openIds,String content){

        if(StringUtils.isBlank(openIds)){
            return ServerResponse.createByErrorMessage("传入的openIds不能为空");
        }

        String jsonMsg = "{\"touser\":[%s],\"msgtype\":\"text\",\"text\":{\"content\":\"%s\"}}";


        String jsonMsgformat = String.format(jsonMsg,openIds,content);

        System.err.println(jsonMsgformat);

        String url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+WeChatUtils.ACCESS_TOKEN;

        String result = HttpClientUtils.sendHttpPostJson(url,jsonMsgformat);
        logger.debug("result1 = "+result);
        WeChatBaseResult weChatBaseResult = JSON.parseObject(result, WeChatBaseResult.class);

        //失败的时候再尝试一次，刷新Access_Token
        if (!WeChatUtils.checkErrcode(weChatBaseResult)) {
            url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+WeChatUtils.ACCESS_TOKEN;
            result = HttpClientUtils.sendHttpPostJson(url,jsonMsgformat);
            logger.debug("result2 = " + result);
            weChatBaseResult = JSON.parseObject(result, WeChatBaseResult.class);
        }
        if(weChatBaseResult.getErrcode() != 0){
            logger.debug("msg:"+weChatBaseResult.getErrmsg());
            return ServerResponse.createByErrorMessage(weChatBaseResult.getErrmsg());
        }
        return ServerResponse.createBySuccessMessage("发送成功");
        }
}
